package com.crazyhat.crazyhat.tasks;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.crazyhat.crazyhat.utils.ScanImage;

/**
 * 图片扫描定时任务
 */
@Component
public class ImageScanTask {
    
    /**
     * 两次扫描最小间隔分钟数
     */
    private final int MinIntervalMinutes=3;

    private static final ReentrantLock lock = new ReentrantLock();

    private static List<String> urlList;

    private final int BATCH_SIZE = 6;

    static{
        urlList=new ArrayList<String>();
    }

    public static void addUrl(List<String> list) {
        if (list!=null) {
            lock.lock();
            try {
                urlList.addAll(list);
            } finally {
                lock.unlock();
            }
        }
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void scanImage() {

        lock.lock();
        List<String> tempList;
        try {
            if (urlList.isEmpty()) {
                return;
            }

            tempList = new ArrayList<>(urlList); // 创建urlList的一个副本
            urlList.clear(); // 清空原始urlList

        } finally {
            lock.unlock();
        }

        System.out.println("开始扫描图片，待扫描的共"+tempList.size()+"张");
        if (tempList.size()<=0) {
            return;
        }
        
        while (tempList.size()>0) {
            
            List<String> list=new ArrayList<String>();

            int count=Math.min(BATCH_SIZE, tempList.size());

            list.addAll(tempList.subList(0, count));

            ScanImage.scheduledScan(list);

            tempList.removeAll(list);
        }
    }
}
